package io.laputa.offer.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.laputa.offer.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Qsh
 * @since 2024/9/14
 */
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        log.info("token: {}", token);
        Map<String, Object> res = new HashMap<>();
        try {
            DecodedJWT decodedJWT = JWTUtil.getInfo(token);
            res.put("state", true);
            res.put("msg", "认证成功");
            res.put("data", decodedJWT.getClaim("username").asString());
            return true;
        } catch (SignatureVerificationException e) {
            log.error(e.getMessage());
            res.put("msg", "无效签名");
        } catch (AlgorithmMismatchException e) {
            log.error(e.getMessage());
            res.put("msg", "算法不一致");
        } catch (TokenExpiredException e) {
            log.error(e.getMessage());
            res.put("msg", "Token已过期");
        } catch (JWTVerificationException e) {
            log.error(e.getMessage());
            res.put("msg", "Token无效");
        }
        res.put("state", false);
        String json = new ObjectMapper().writeValueAsString(res);
        response.getWriter().print(json);
        return false;
    }
}
